<template>
    <div>
        <div>
            <input type="checkbox" @change="handleChange"><label>全选</label>
        </div>
        <ul class="shop-item">
            <li v-for="(item,i) in shopcar" :key="item.name">
                <div>
                    <input type="checkbox" v-model="item.isChecked">
                </div>
                <img :src="item.image" alt="" />
                <p>{{ item.name }}</p>
                <p>￥{{item.price}}</p>
                <div>
                    <input type="button" value="-" @click="decrement(item)">
                    <input type="text" v-model="item.count" >
                    <input type="button" value="+" @click="increment(item)">
                </div>  
                <p>￥{{(item.price * item.count).toFixed(2)}}</p>
                <a href="#" @click="handleRemove(i)">删除</a>
            </li>
        </ul>
        <div>
            <h2 class="total-price">总价：￥{{totalPrice.toFixed(2)}}</h2>
        </div>
    </div>
</template>

<script setup>
import { computed, reactive } from "vue";
import t1 from "../assets/javascript高级程序设计.jpg";
import t2 from "../assets/javascript权威指南.jpg";
import t3 from "../assets/javascript悟道.jpg";
const shopcar = reactive([
    { image: t1, name: "javascript高级程序设计", price: 106.5, count: 1,isChecked:false },
    { image: t2, name: "javascript权威指南", price: 116.1, count: 1,isChecked:false },
    { image: t3, name: "javascript悟道", price: 89.4, count: 1,isChecked:false },
]);

const totalPrice = computed(() => {
    return shopcar.reduce((total,current) => {
        if(current.isChecked){
            return total + current.price * current.count;       
        }
        return total;     
    },0);
})

function handleChange(e){
    shopcar.forEach((item) => {
        item.isChecked = e.target.checked;
    })
}
function handleRemove(i){
    shopcar.splice(i,1);
}

function increment(item){
    item.count++;
}
function decrement(item){
    if(item.count <= 0){
        item.count = 0;
        return;
    }
    item.count--;
}


</script>

<style>
.shop-item li{
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}
.shop-item li>*{
    margin-right:30px;
}
.shop-item li input[type=text]{
    width:50px;
}
.shop-item img{
    width:70px;
    height:100px;
}
.total-price{
    color:red;
}
</style>